<?php
/**
 * Created by PhpStorm.
 * User: lenovo-7
 * Date: 2015/6/18
 * Time: 10:44
 */

class inman_api_order extends inman_api_base{

    /**
     * 4.1	订单列表
     */
    public function getOrderList($params,&$service){
        if(!$this->check_sid($params['sid']) ){
            return $service->send_user_error('100001','error sid');
        }
        $member_id = kernel::single('b2c_user_object')->get_member_id();
        $type = $params['type']?$params['type']:0;
        $db = kernel::database();
        if($type == 0){
            $orders = $db->select('select * from sdb_b2c_orders where member_id='.$member_id);
        }
        if($type == 1){
            $orders = $db->select('select * from sdb_b2c_orders where pay_status=0 and member_id='.$member_id);
        }
        if($type == 2){
            $orders = $db->select('select * from sdb_b2c_orders where ship_status in(0,1,2) member_id='.$member_id);
        }
        foreach($orders as $k=>$v){
            $order_items = $db->select('select * from sdb_b2c_order_items where order_id='.$v['order_id']);
            //$order_objects = $db->select('select * from sdb_b2c_order_objects where order_id='.$v['order_id']);
            $prepare_order = $db->selectrow('select * from sdb_preparesell_prepare_order where order_id='.$v['order_id']);
            $return_product = $db->selectrow('select * from sdb_aftersales_archive_return_product where order_id='.$v['order_id']);

            $return['order_list'][$k]['order_sn'] = $v['order_id'];	//	订单编号
            $return['order_list'][$k]['trans_user_rank'] = '????';	//	下单是时用户户等级描述
            $return['order_list'][$k]['status'] = $v['status'] == 'active'?'活动订单':($v['status'] == 'dead'?'已作废':'已完成');	//	订单状态
            $return['order_list'][$k]['status_type'] = $v['status'];	//	订单状态
            $return['order_list'][$k]['order_time'] = date('Y-m-d',$v['createtime']);	//	订单添加时间
            $return['order_list'][$k]['order_timestamp'] = $v['createtime'];	//	订单添加时间(时间戳)
            $return['order_list'][$k]['goods_amount'] = $v['cost_item'];	//	商品总金额
            $return['order_list'][$k]['order_amount'] = $v['final_amount'];	//	支付金额
            $return['order_list'][$k]['total_fee'] = $v['total_amount'];	//	订单金额
            $return['order_list'][$k]['order_status'] = $v['status'];	//	订单状态
            $return['order_list'][$k]['pay_status'] = $v['pay_status'];	//	支付状态
            $return['order_list'][$k]['shipping_status'] = $v['ship_status'];	//	商品配送状态
            $return['order_list'][$k]['type'] = $v['promotion_type'];	//	商品类型
            $return['order_list'][$k]['deposit'] = $prepare_order['preparesell_price'];	//	预售定金
            $return['order_list'][$k]['promo_price'] = $prepare_order['promotion_price'];	//	预售价格
            $return['order_list'][$k]['balance'] = $prepare_order['promotion_price'] - $prepare_order['preparesell_price'];	//	预售尾款
            $return['order_list'][$k]['deposit_start_timestamp'] = $prepare_order['begin_time'];	//	付定金开始时间
            $return['order_list'][$k]['deposit_end_timestamp'] = $prepare_order['end_time'];	//	付定金结束时间
            $return['order_list'][$k]['balance_start_timestamp'] = $prepare_order['begin_time_final'];	//	付尾款开始时间
            $return['order_list'][$k]['balance_end_timestamp'] = $prepare_order['end_time_final'];	//	付尾款结束时间
            $return['order_list'][$k]['is_deposit_pay'] = '????';	//	是否已付定金
            $return['order_list'][$k]['is_remaining_balace_pay'] = '????';	//	是否已付尾款
            foreach($order_items as $kk=>$vv){                              //	订单商品列表
                $return['order_list'][$k]['order_goods_list'][$kk]['order_goods_id'] = $vv['goods_id'];	//	订单商品id
                $return['order_list'][$k]['order_goods_list'][$kk]['goods_sn'] = $vv['bn'];	//	商品编号
                $return['order_list'][$k]['order_goods_list'][$kk]['goods_name'] = $vv['name'];	//	商品名称

                $addon_arr = unserialize($vv['addon']);
                $return['order_list'][$k]['order_goods_list'][$kk]['color_code'] = $addon_arr['product_attr']['1']['value'];	//	颜色编号
                $return['order_list'][$k]['order_goods_list'][$kk]['color_name'] = $addon_arr['product_attr']['1']['value'];	//	颜色名称
                $return['order_list'][$k]['order_goods_list'][$kk]['size_name'] = $addon_arr['product_attr']['3']['value'];	//	尺寸名称

                $return['order_list'][$k]['order_goods_list'][$kk]['shop_price'] = $vv['price'];	//	商品价格
                $return['order_list'][$k]['order_goods_list'][$kk]['goods_price'] = $vv['g_price'];	//	商品价格
                $return['order_list'][$k]['order_goods_list'][$kk]['transaction_price'] = $vv['price'];	//	成交价格
                $return['order_list'][$k]['order_goods_list'][$kk]['goods_number'] = $vv['nums'];	//	商品数量
                $return['order_list'][$k]['order_goods_list'][$kk]['total_price'] = $vv['amount'];	//	总价格

                //$goods_info = $db->selectrow('select image_default_id from sdb_b2c_goods where goods_id='.$vv['goods_id']);
                //$return['order_list'][$k]['order_goods_list'][$kk]['img_url'] = base_storager::image_path($goods_info['image_default_id']);	//	商品图片
                $goods_imgs = $this->_get_gids_image(false,$vv['goods_id']);
                $return['order_list'][$k]['order_goods_list'][$kk]['img_url'] = $goods_imgs[$vv['goods_id']]['l_url'];	//	商品图片
                $can_comment = $this->_checkcomments(array('goods_id'=>$vv['goods_id']),&$msg);
                $return['order_list'][$k]['order_goods_list'][$kk]['can_comment'] = $can_comment['status'];	//	是否可评论
                $return['order_list'][$k]['order_goods_list'][$kk]['is_returned'] = !empty($return_product);	//	是否有退换
                $return['order_list'][$k]['order_goods_list'][$kk]['return_type'] = $return_product['type'];	//	退换类型

                $return['order_list'][$k]['order_goods_list'][$kk]['return_info']['return_sn'] = $return_product['return_bn'];	//	退款号
                $return['order_list'][$k]['order_goods_list'][$kk]['return_info']['status'] = $return_product['status'];	//	状态
                $return['order_list'][$k]['order_goods_list'][$kk]['return_info']['status_name'] = $return_product['status'];	//	状态名称
                $return['order_list'][$k]['order_goods_list'][$kk]['return_info']['number	int'] = '????';	// 数量
                $return['order_list'][$k]['order_goods_list'][$kk]['return_info']['apply_time'] = $return_product['add_time'];	//	申请时间
                $return['order_list'][$k]['order_goods_list'][$kk]['return_info']['return_total_fee'] = '????';	//	退款金额
            }
        }

        return $return;

    }

    /**
     * 4.2 订单详情
     */
    public function getOrderDetail($params,&$service){
        if(!$this->check_sid($params['sid']) ){
            return $service->send_user_error('100001','error sid');
        }
        if(empty($params['order_sn']) ){
            return $service->send_user_error('参数错误，order_sn不能为空');
        }
        $order_id = $params['order_sn'];
        $db = kernel::database();
        $order = $db->selectrow('select * from sdb_b2c_orders where order_id ='.$order_id);
        $order_items = $db->select('select * from sdb_b2c_order_items where order_id='.$order['order_id']);
        //$order_objects = $db->select('select * from sdb_b2c_order_objects where order_id='.$v['order_id']);
        $prepare_order = $db->selectrow('select * from sdb_preparesell_prepare_order where order_id='.$order['order_id']);
        $return_product = $db->selectrow('select * from sdb_aftersales_archive_return_product where order_id='.$order['order_id']);

        $return['order_sn'] = $order['order_id'];	//	订单编号
        $return['trans_user_rank'] = '????';	//	下单是时用户户等级描述
        $return['status'] = $order['status'] == 'active'?'活动订单':($order['status'] == 'dead'?'已作废':'已完成');	//	订单状态
        $return['status_type'] = $order['status'];	//	订单状态
        $return['order_time'] = date('Y-m-d',$order['createtime']);	//	订单添加时间
        $return['order_timestamp'] = $order['createtime'];	//	订单添加时间(时间戳)
        $return['goods_amount'] = $order['cost_item'];	//	商品总金额
        $return['order_amount'] = $order['final_amount'];	//	支付金额
        $return['total_fee'] = $order['total_amount'];	//	订单金额
        $return['discount_amount'] = $order['discount'];	//	折扣金额
        $return['order_status'] = $order['status'];	//	订单状态
        $return['pay_status'] = $order['pay_status'];	//	支付状态
        $return['pay_name'] = $order['payment'];	//	付款方式
        $return['pay_code'] = $order['payment'];	//	付款方式
        $return['consignee'] = $order['ship_name'];	//	收货人
        $return['mobile'] = $order['ship_mobile'];	//	联系电话
        $return['address'] = $order['ship_addr'];	//	地址
        $return['shipping_fee'] = $order['cost_freight'];	//	配送费用
        $return['shipping_status'] = $order['ship_status'];	//	商品配送状态
        $return['type'] = $order['promotion_type'];	//	商品类型
        $return['deposit'] = $prepare_order['preparesell_price'];	//	预售定金
        $return['promo_price'] = $prepare_order['promotion_price'];	//	预售价格
        $return['balance'] = $prepare_order['promotion_price'] - $prepare_order['preparesell_price'];	//	预售尾款
        $return['deposit_start_timestamp'] = $prepare_order['begin_time'];	//	付定金开始时间
        $return['deposit_end_timestamp'] = $prepare_order['end_time'];	//	付定金结束时间
        $return['balance_start_timestamp'] = $prepare_order['begin_time_final'];	//	付尾款开始时间
        $return['balance_end_timestamp'] = $prepare_order['end_time_final'];	//	付尾款结束时间
        $return['is_deposit_pay'] = '????';	//	是否已付定金
        $return['is_remaining_balace_pay'] = '????';	//	是否已付尾款
        foreach($order_items as $kk=>$vv){                              //	订单商品列表
            $return['order_goods_list'][$kk]['order_goods_id'] = $vv['goods_id'];	//	订单商品id
            $return['order_goods_list'][$kk]['goods_sn'] = $vv['bn'];	//	商品编号
            $return['order_goods_list'][$kk]['goods_name'] = $vv['name'];	//	商品名称

            $addon_arr = unserialize($vv['addon']);
            $return['order_goods_list'][$kk]['color_code'] = $addon_arr['product_attr']['1']['value'];	//	颜色编号
            $return['order_goods_list'][$kk]['color_name'] = $addon_arr['product_attr']['1']['value'];	//	颜色名称
            $return['order_goods_list'][$kk]['size_name'] = $addon_arr['product_attr']['3']['value'];	//	尺寸名称

            $return['order_goods_list'][$kk]['shop_price'] = $vv['price'];	//	商品价格
            $return['order_goods_list'][$kk]['goods_price'] = $vv['g_price'];	//	商品价格
            $return['order_goods_list'][$kk]['transaction_price'] = $vv['price'];	//	成交价格
            $return['order_goods_list'][$kk]['goods_number'] = $vv['nums'];	//	商品数量
            $return['order_goods_list'][$kk]['total_price'] = $vv['amount'];	//	总价格

            $goods_info = $db->selectrow('select image_default_id from sdb_b2c_goods where goods_id='.$vv['goods_id']);
            $goods_imgs = $this->_get_gids_image(false,$vv['goods_id']);
            $return['order_goods_list'][$kk]['img_url'] = $goods_imgs[$vv['goods_id']]['l_url'];	//	商品图片

            $can_comment = $this->_checkcomments(array('goods_id'=>$vv['goods_id']),&$msg);
            $member_comments = $db->selectrow('select * from sdb_b2c_member_comments where object_type="discuss" and order_id='.$order_id.' and product_id='.$vv['product_id']);
            $return['order_goods_list'][$kk]['can_comment'] = $can_comment['status'];	//	是否可评论
            $return['order_goods_list'][$kk]['user_comment']['user_name'] = $member_comments['author'];	//	用户名
            $return['order_goods_list'][$kk]['user_comment']['attr'] = '????';	//
            $return['order_goods_list'][$kk]['user_comment']['comment_time'] = date('Y-m-d',$member_comments['time']);	//	评论时间
            $return['order_goods_list'][$kk]['user_comment']['comment_timestamp'] = $member_comments['time'];	//	评论时间戳
            $return['order_goods_list'][$kk]['user_comment']['content'] = $member_comments['comment'];	//	评论内容
            $return['order_goods_list'][$kk]['user_comment']['img_list']['thumb'] = $goods_imgs[$vv['goods_id']]['s_url'];	//	缩略图
            $return['order_goods_list'][$kk]['user_comment']['img_list']['origin'] = base_storager::image_path($goods_info['image_default_id']);	//	原图
            $return['order_goods_list'][$kk]['user_comment']['is_answer'] = '????';	//	大茵是否回答
            $return['order_goods_list'][$kk]['user_comment']['answer'] = '????';	//	大茵回答内容
            $return['order_goods_list'][$kk]['user_comment']['is_check'] = $member_comments['disabled'];	//	评论是否通过审核

            $return['order_goods_list'][$kk]['is_returned'] = !empty($return_product);	//	是否有退换
            $return['order_goods_list'][$kk]['return_type'] = $return_product['type'];	//	退换类型
            $return['order_goods_list'][$kk]['return_info']['return_sn'] = $return_product['return_bn'];	//	退款号
            $return['order_goods_list'][$kk]['return_info']['status'] = $return_product['status'];	//	状态
            $return['order_goods_list'][$kk]['return_info']['status_name'] = $return_product['status'];	//	状态名称
            $return['order_goods_list'][$kk]['return_info']['number	int'] = '????';	// 数量
            $return['order_goods_list'][$kk]['return_info']['apply_time'] = $return_product['add_time'];	//	申请时间
            $return['order_goods_list'][$kk]['return_info']['return_total_fee'] = '????';	//	退款金额
        }

        return $return;

    }

    /**
     * 4.3 订单结算(立即购买)
     * 	参数            必选	      类型及范围	    说明
        sid	            是	       string	    session id
        sku_sn	        是	       string	    库存编号  eg:P4C84C14E1AB67
        goods_number	是	       int	        商品数量
     *
     * 4.4 订单结算(购物车)
     *  sid	            是	       string	    session id
        cart_id_list	是	       string	    购物车id列表，多个id用逗号(,)分隔  eg:goods_42_296,goods_58_403,goods_96_548


     */
    public function settle($params,&$service)
    {
        if (!$member_id = $this->check_sid($params['sid'])) {
            return $service->send_user_error('100001', 'error sid');
        }
        $db = kernel::database();

        if(empty($params['cart_id_list'])){
            if(empty($params['sku_sn']) || empty($params['goods_number'])){
                return $service->send_user_error('参数缺少');
            }else{
                $sku_sn = $params['sku_sn'];
                $goods_number[] = $params['goods_number'];
                $products[] = $db->selectrow('select * from sdb_b2c_products where bn="'.$sku_sn.'"');
            }
        }else{
            $cart_id_list = explode(',',$params['cart_id_list']);
            foreach($cart_id_list as $k=>$v){
                $cart_objects[$k] = $db->selectrow('select * from sdb_b2c_cart_objects member_id = '.$member_id.' and where obj_ident="'.$v.'"');
                $goods_number[$k] = $cart_objects[$k]['quantity'];
                $cart_id_arr = explode('_',$v);
                $products[$k] = $db->selectrow('select * from sdb_b2c_products where product_id='.$cart_id_arr[2]);
            }
        }
        $total_money = 0;
        foreach($products as $k=>$v){   //商品列表
            $goods = $db->selectrow('select * from sdb_b2c_goods where goods_id='.$v['goods_id']);
            $spec_info = unserialize($v['spec_desc']);
            $return['goods_list'][$k]['sku_sn'] = $v['bn'];	//	库存编号
            $return['goods_list'][$k]['goods_number'] = $goods_number[$k];	//	商品数量
            $return['goods_list'][$k]['goods_sn'] = $goods['bn'];	//	商品编号
            $return['goods_list'][$k]['goods_name'] = $v['name'];	//	商品名称
            $return['goods_list'][$k]['color_code'] = $spec_info['spec_value_id'][1];	//	颜色编号
            $return['goods_list'][$k]['color_name'] = $spec_info['spec_value'][1];	//	颜色名称
            $return['goods_list'][$k]['size_name'] =  $spec_info['spec_value'][3];	//	尺寸名称
            $return['goods_list'][$k]['goods_price'] = $v['mktprice'];	//	商品价格
            $return['goods_list'][$k]['shop_price'] = $v['price'];	//	商品价格
            $return['goods_list'][$k]['transaction_price'] = $v['price'];	//	成交价格
            $return['goods_list'][$k]['total_price'] = $v['price']*$goods_number[$k];	//	总价
            $return['goods_list'][$k]['img_url'] = base_storager::image_path($goods['image_default_id']);	//	商品图片
            $total_money += $return['goods_list'][$k]['total_price'];
        }

        $sales_rule_order  = $db->select('select * from sdb_b2c_sales_rule_order');
        foreach($sales_rule_order as $k=>$v){ // 促销列表
            $return['promo_list'][$k]['pr_id'] = $v['rule_id'];	//	促销id
            $return['promo_list'][$k]['pr_name'] = $v['name'];	//	促销名称
        }

        //现金券列表
        $return['coupon_list'][]['card_sn']= '';	//	卡号
        $return['coupon_list'][]['start_time']= '';	//	有效期开始时间
        $return['coupon_list'][]['end_time']= '';	//	有效期结束时间
        $return['coupon_list'][]['cc_amount']= '';	//	面额
        $return['coupon_list'][]['desc']= '';	//	描述

        $b2c_coupons = $db->select('select * from sdb_b2c_coupons');
        foreach($b2c_coupons as $k=>$v){     //	优惠券列表
            $return['vouchers_list']['card_sn'] ='';	//	卡号
            $return['vouchers_list']['start_time'] ='';	//	有效期开始时间
            $return['vouchers_list']['end_time'] ='';	//	有效期结束时间
            $return['vouchers_list']['cv_amount'] ='';	//	面额
            $return['vouchers_list']['lowest_amount'] ='';	//	使用门槛
            $return['vouchers_list']['desc'] ='';	//	描述
        }


        $return['total_money'] = $total_money;	//	总金额
        $return['trans_user_rank'] = '????';	//	用户当前等级描述
        $return['discount'] = 0;	//	折扣金额
        $return['no_shipping_fee_amount'] = $total_money;	//	不计运费时的总费用
        $return['shipping_fee'] = 0;	//	配送费用
        $return['new_shipping_fee'] = 0;	//	运费
        $return['pay_money	float'] = $total_money;	//需要支付金额

        $gifts = $db->select('select * from sdb_gift_ref');
        foreach($gifts as $k=>$v){  // 赠品列表
            $ginfo = $db->selectrow('select * from sdb_b2c_goods where goods_id='.$v['goods_id']);
            $pinfo = $db->select('select * from sdb_b2c_products where goods_id='.$v['goods_id']);
            $return['gift'][$k]['goods_sn']	= $ginfo['bn']; //	商品编号
            $return['gift'][$k]['goods_name'] = $ginfo['name'];	//	商品名称
            $return['gift'][$k]['shop_price'] = $ginfo['price'];	//	商品价格
            $return['gift'][$k]['img_url'] = base_storager::image_path($ginfo['image_default_id']);;	//	商品图片
            $return['gift'][$k]['number'] = $ginfo['store'];	//	商品数量
            $return['gift'][$k]['transaction_price'] = $ginfo['price'];	//	成交价格
            foreach($pinfo as $kk=>$vv){
                $spec_desc = unserialize($vv['spec_desc']);
                $return['gift'][$k]['goods_color'][$kk]['color_code'] = $spec_desc['spec_value_id']['1'];	//	颜色编码
                $return['gift'][$k]['goods_color'][$kk]['color_name'] = $spec_desc['spec_value']['1'];	//	颜色名称
                $return['gift'][$k]['goods_size'][$kk]['size_code']  = $spec_desc['spec_value_id']['3'];	//	尺寸编码
                $return['gift'][$k]['goods_size'][$kk]['size_name']  = $spec_desc['spec_value']['3'];	//	尺寸名称
                $return['gift'][$k]['inventory_info']['sku_sn'] = $vv['bn'];
                $return['gift'][$k]['inventory_info']['color_code'] = $spec_desc['spec_value_id']['1'];
                $return['gift'][$k]['inventory_info']['size_code'] = $spec_desc['spec_value_id']['3'];
                $return['gift'][$k]['inventory_info']['available_number'] = $vv['store'];
            }

        }
        $return['deduction_integral'] = 0;	//	使用的积分
        $return['integral_money'] = 0;	//	积分可抵扣的金额
        return $return;

    }

    /**
     * 4.5 取消订单
     */
    public function cancelOrder($params,&$service)
    {
        if(!$this->check_sid($params['sid']) ){
            return $service->send_user_error('100001','error sid');
        }
        if(!$params['order_sn']){
            return $service->send_user_error('参数错误，order_sn不能为空');
        }else{
            $order_id = $params['order_sn'];
        }
        $arrMember = kernel::single('b2c_user_object')->get_current_member();
        //开启事务处理
        $db = kernel::database();
        $transaction_status = $db->beginTransaction();
        $mdl_order = app::get('b2c')->model('orders');
        $sdf_order_member_id = $mdl_order->getRow('member_id', array('order_id'=>$order_id));
        if($sdf_order_member_id['member_id'] != $arrMember['member_id'])
        {
            $db->rollback();
            $service->send_user_error("请勿取消别人的订单");
            return;
        }
        $obj_checkorder = kernel::service('b2c_order_apps', array('content_path'=>'b2c_order_checkorder'));
        if (!$obj_checkorder->check_order_cancel($order_id,'',$message))
        {
            $db->rollback();
            $service->send_user_error($message);
        }

        $sdf['order_id'] = $order_id;
        $sdf['op_id'] = $arrMember['member_id'];
        $sdf['opname'] = $arrMember['uname'];
        $sdf['account_type'] = 'member';

        $b2c_order_cancel = kernel::single("b2c_order_cancel");
        if ($b2c_order_cancel->generate($sdf))
        {
            if($order_object = kernel::service('b2c_order_rpc_async')){
                $order_object->modifyActive($sdf['order_id']);
            }
            $db->commit($transaction_status);
            $return['error_code'] = 0;
        }
        else
        {
            $db->rollback();
            $return['error_code'] = 1;
        }

        return $return;
    }

    /**
     * 4.6 添加订单（立即购买)
        参数 必选	类型及范围	说明
     *  sid	是	string	session id
     ?  type	是	int	添加订单（立即购买）type为2
     *  address_id	是	int	地址id
     *  payment	是	string	支付方式alipay,cod unionpay,wxpay
     ?  integral	是	int	使用积分数
     ?  gift_sku	是	string	赠品库存编号
     *  goods_sku	是	string	商品库存编号   ——> product_id 货品id
     *  goods_number	是	int	商品数量
     *  pay_note	否	string	留言

     */
    public function addNow($params,&$service)
    {
        if(!$member_id = $this->check_sid($params['sid']) ){
            return $service->send_user_error('100001','error sid');
        }
        if(!$params['product_id']){
            return $service->send_user_error('参数错误，product_id不能为空.');
        }
        if(!$params['goods_number']){
            return $service->send_user_error('参数错误，goods_number不能为空.');
        }
        if(!$params['address_id']){
            return $service->send_user_error('参数错误，address_id不能为空.');
        }
        if(!$params['payment']){
            return $service->send_user_error('参数错误，payment不能为空.');
        }
        $login_name = kernel::single('b2c_user_object')->get_member_name();
        $product_id = $params['product_id'];
        $goodsnum = $params['goods_number'];
        $addr_id = $params['address_id'];
        $payment = $params['payment'];
        $pay_note = $params['pay_note'];

        $obj_pam_members = app::get('pam')->model('members');
        $aUser = $obj_pam_members->dump(array('login_account' => $login_name));
        $aUser['account_id'] = $aUser['member_id'];
        $order['member_id'] = $aUser['account_id'];
        // 得到当前会员的积分
        $member_point = $aUser['score']['total'];
        $aUser['pam_account']['account_id'] = 0;
        $aUser['member_lv']['member_group_id'] = 0;
        $_SESSION['tmp_admin_create_order'] = array();
        $_SESSION['tmp_admin_create_order']['member'] = $aUser;


        $data = array();
        // 生成购物车数据
        $mdl_product = app::get('b2c')->model('products');

        $product = $mdl_product->dump($product_id,'*');
        if(!$product){
            return $service->send_user_error('货品不存在，请检查product_id.');
        }
        if ( ($product['store']-$product['freez']) < $goodsnum )
        {
            return $service->send_user_error('库存不足，请检查！');
        }
        $data['goods'][] = array('goods'=>array(
            'goods_id'=>$product['goods_id'],
            'product_id'=>$product['product_id'],
            'adjunct' => 'na',
            'num' =>$goodsnum
        ));

        $obj_mCart = app::get('b2c')->model('cart');
        $member_indent = md5(kernel::single('base_session')->sess_id());
        $obj_mCart->set_cookie_cart_arr($data, $member_indent);
        $arr_cart_objects = $obj_mCart->get_cart_object($data);

        if (!isset($arr_cart_objects['cart_status']) || !$arr_cart_objects['cart_status'] || $arr_cart_objects['cart_status'] == 'true')
        {
            if($aUser['account_id'])
            {
                $member_addrs = app::get('b2c')->model('member_addrs');
                $address = $member_addrs->getRow('*',array('addr_id'=>$addr_id));

                $_POST['member_id'] = $aUser['account_id'];
                $_POST['delivery']['addr_id'] = $address['addr_id'];
                $_POST['delivery']['ship_area'] = $address['area'];

                $ship_area_arr = explode(':',$address['area']);
                $area_arr = explode('/',$ship_area_arr[1]);
                $_POST['delivery']['ship_addr_area'] = implode('',$area_arr);

                $_POST['delivery']['ship_addr'] = $address['addr'];
                $_POST['delivery']['ship_zip'] = $address['zip'];
                $_POST['delivery']['ship_name'] = $address['name'];
                $_POST['delivery']['ship_mobile'] = $address['mobile'];
                $_POST['delivery']['ship_tel'] = $address['tel'];
                $_POST['delivery']['day'] = '任意日期';
                $_POST['delivery']['specal_day'] = '';
                $_POST['delivery']['time'] = '任意时间段';
                $_POST['delivery']['shipping_id'] = '1';
                $_POST['def_addr'] = $address['def_addr'];
                $_POST['memo'] = $pay_note;
                $_POST['payment']['pay_app_id'] = $payment;
            }
        }

        $obj_mCart = app::get('b2c')->model('cart');
        $member_indent = md5($_POST['member_id'] . kernel::single('base_session')->sess_id());
        $data = $obj_mCart->get_cookie_cart_arr($member_indent,$_POST['member_id']);

        $objCarts = $obj_mCart->get_cart_object($data);
        $is_empty = $obj_mCart->is_empty($objCarts);
        if ($is_empty)
        {
            return $service->send_user_error('购物车为空，操作失败！');
        }

        $order = app::get('b2c')->model('orders');
        $_POST['order_id'] = $order_id = $order->gen_id();
        $order_data = array();

        //加入货币类型。否则会出现前台显示不支持此种支付方式
        $objCurrency = app::get('ectools')->model("currency");
        $aCur = $objCurrency->getDefault();
        $_POST['payment']['currency'] = $aCur['cur_code'];

        $obj_order_create = kernel::single("b2c_order_create");
        $order_data = $obj_order_create->generate($_POST, $member_indent, $msg, $objCarts);

        $result = $obj_order_create->save($order_data, $msg);
        // 与中心交互
        /*$obj_rpc_request_service = kernel::service('b2c.rpc.send.request');

        if ($obj_rpc_request_service && method_exists($obj_rpc_request_service, 'rpc_caller_request'))
        {
            if ($obj_rpc_request_service instanceof b2c_api_rpc_request_interface)
                $obj_rpc_request_service->rpc_caller_request($order_data,'create');
        }
        else
        {
            $obj_order_create->rpc_caller_request($order_data);
            }*/
        //新的版本控制api
        $obj_apiv = kernel::single('b2c_apiv_exchanges_request');
        $obj_apiv->rpc_caller_request($order_data, 'ordercreate');

        // 取到日志模块
        $log_text = "";
        if ($result)
        {
            $log_text = app::get('b2c')->_("订单创建成功！");
        }
        else
        {
            $log_text = app::get('b2c')->_("订单创建失败！");
        }
        $orderLog = app::get('b2c')->model("order_log");
        $sdf_order_log = array(
            'rel_id' => $order_id,
            'op_id' => $this->user->user_id,
            'op_name' => $this->user->user_data['account']['login_name'],
            'alttime' => time(),
            'bill_type' => 'order',
            'behavior' => 'creates',
            'result' => ($result) ? 'SUCCESS' : 'FAILURE',
            'log_text' => $log_text,
        );

        $log_id = $orderLog->save($sdf_order_log);

        if ($result)
        {
            // 订单成功后清除购物车的的信息
            $cart_model = app::get('b2c')->model('cart');
            $cart_model->del_cookie_cart_arr($member_indent);

            // 得到物流公司名称
            if ($order_data['order_objects'])
            {
                $itemNum = 0;
                $good_id = "";
                $goods_name = "";
                foreach ($order_data['order_objects'] as $arr_objects)
                {
                    if ($arr_objects['order_items'])
                    {
                        if ($arr_objects['obj_type'] == 'goods')
                        {
                            $obj_goods = app::get('b2c')->model('goods');
                            $good_id = $arr_objects['order_items'][0]['goods_id'];
                            $arr_goods = $obj_goods->dump($good_id);
                        }

                        foreach ($arr_objects['order_items'] as $arr_items)
                        {
                            $itemNum = kernel::single('ectools_math')->number_plus(array($itemNum, $arr_items['quantity']));
                            if ($arr_objects['obj_type'] == 'goods')
                            {
                                if ($arr_items['item_type'] == 'product')
                                    $goods_name .= $arr_items['name'] . ($arr_items['products']['spec_info'] ? '(' . $arr_items['products']['spec_info'] . ')' : '') . '(' . $arr_items['quantity'] . ')';
                            }
                        }
                    }
                }
                $obj_dlytype = app::get('b2c')->model('dlytype');
                $arr_dlytype = $obj_dlytype->dump($order_data['shipping']['shipping_id'], 'dt_name');

                if ($order_data['member_id'])
                {
                    $login_name = kernel::single('b2c_user_object')->get_member_name(null,$order_data['member_id']);
                }
                $arr_updates = array(
                    'order_id' => $order_id,
                    'total_amount' => $order_data['total_amount'],
                    'shipping_id' => $arr_dlytype['dt_name'],
                    'ship_mobile' => $order_data['consignee']['mobile'],
                    'ship_tel' => $order_data['consignee']['telephone'],
                    'ship_addr' => $order_data['consignee']['addr'],
                    'ship_email' => $order_data['consignee']['email'] ? $order_data['consignee']['email'] : '',
                    'ship_zip' => $order_data['consignee']['zip'],
                    'ship_name' => $order_data['consignee']['name'],
                    'member_id' => $order_data['member_id'] ? $order_data['member_id'] : 0,
                    'uname' => (!$order_data['member_id']) ? app::get('b2c')->_('顾客') : $login_name,
                    'itemnum' => count($order_data['order_objects']),
                    'goods_id' => $good_id,
                    'goods_url' => kernel::base_url(1).kernel::url_prefix().app::get('site')->router()->gen_url(array('app'=>'b2c','ctl'=>'site_product','act'=>'index','arg0'=>$good_id)),
                    'thumbnail_pic' => base_storager::image_path($arr_goods['image_default_id']),
                    'goods_name' => $goods_name,
                    'ship_status' => '',
                    'pay_status' => 'Nopay',
                    'is_frontend' => false,
                );
                $order->fireEvent('create', $arr_updates, $order_data['member_id']);
            }
        }

        if ($result)
        {
            $order_num = $order->count(array('member_id' => $order_data['member_id']));
            $obj_mem = app::get('b2c')->model('members');
            $obj_mem->update(array('order_num'=>$order_num), array('member_id'=>$order_data['member_id']));
            return $return = array('order_sn'=>$order_id);
        }
    }

    /**
     * 4.7 添加订单（购物车)
     * 	                必选	类型及范围	说明
        sid	            是	string	    session id
     ?  type	        是	int	        添加订单（购物车）type为1
        cart_id_list    是	string	    购物车ID列表
        address_id	    是	int	        地址id
        payment	        是	string	    支付方式alipay,cod unionpay,wxpay
     ?  integral	    是	int	        使用积分数
     ?  os	            否	string	    操作系统，android或ios
     */
    public function add($params,&$service)
    {
        if(!$member_id = $this->check_sid($params['sid']) ){
            return $service->send_user_error('100001','error sid');
        }
        if(!$params['address_id']){
            return $service->send_user_error('参数错误，address_id不能为空.');
        }
        if(!$params['payment']){
            return $service->send_user_error('参数错误，payment不能为空.');
        }
        if(!$params['cart_id_list']){
            return $service->send_user_error('参数错误，cart_id_list不能为空.');
        }
        $login_name = kernel::single('b2c_user_object')->get_member_name();
        $addr_id = $params['address_id'];
        $payment = $params['payment'];
        $pay_note = '';
        $cart_id_list = explode(',',$params['cart_id_list']);
        $db = kernel::database();
        foreach($cart_id_list as $k=>$v){
            $cart_objects[$k] = $db->selectrow('select * from sdb_b2c_cart_objects where member_id = '.$member_id.' and obj_ident="'.$v.'"');
            if(empty($cart_objects[$k])){
                return $service->send_user_error('购物车ID不存在.');
            }
            $goods_num[$k] = $cart_objects[$k]['quantity'];
            $cart_id_arr = explode('_',$v);
            $product_ids[$k] = $cart_id_arr[2];
        }

        $obj_pam_members = app::get('pam')->model('members');
        $aUser = $obj_pam_members->dump(array('login_account' => $login_name));
        $aUser['account_id'] = $aUser['member_id'];
        $order['member_id'] = $aUser['account_id'];
        // 得到当前会员的积分
        $member_point = $aUser['score']['total'];
        $aUser['pam_account']['account_id'] = 0;
        $aUser['member_lv']['member_group_id'] = 0;
        $_SESSION['tmp_admin_create_order'] = array();
        $_SESSION['tmp_admin_create_order']['member'] = $aUser;


        $data = array();
        // 生成购物车数据
        $mdl_product = app::get('b2c')->model('products');
        foreach($product_ids as $k=>$product_id) {
            $product = $mdl_product->dump($product_id, '*');
            if (($product['store'] - $product['freez']) < $goods_num[$k]) {
                return $service->send_user_error('库存不足，请检查！');
            }
            $data['goods'][] = array('goods' => array(
                'goods_id' => $product['goods_id'],
                'product_id' => $product['product_id'],
                'adjunct' => 'na',
                'num' => $goods_num[$k]
            ));
        }
        $obj_mCart = app::get('b2c')->model('cart');
        $member_indent = md5(kernel::single('base_session')->sess_id());
        $obj_mCart->set_cookie_cart_arr($data, $member_indent);
        $arr_cart_objects = $obj_mCart->get_cart_object($data);

        if (!isset($arr_cart_objects['cart_status']) || !$arr_cart_objects['cart_status'] || $arr_cart_objects['cart_status'] == 'true')
        {
            if($aUser['account_id'])
            {
                $member_addrs = app::get('b2c')->model('member_addrs');
                $address = $member_addrs->getRow('*',array('addr_id'=>$addr_id));

                $_POST['member_id'] = $aUser['account_id'];
                $_POST['delivery']['addr_id'] = $address['addr_id'];
                $_POST['delivery']['ship_area'] = $address['area'];

                $ship_area_arr = explode(':',$address['area']);
                $area_arr = explode('/',$ship_area_arr[1]);
                $_POST['delivery']['ship_addr_area'] = implode('',$area_arr);

                $_POST['delivery']['ship_addr'] = $address['addr'];
                $_POST['delivery']['ship_zip'] = $address['zip'];
                $_POST['delivery']['ship_name'] = $address['name'];
                $_POST['delivery']['ship_mobile'] = $address['mobile'];
                $_POST['delivery']['ship_tel'] = $address['tel'];
                $_POST['delivery']['day'] = '任意日期';
                $_POST['delivery']['specal_day'] = '';
                $_POST['delivery']['time'] = '任意时间段';
                $_POST['delivery']['shipping_id'] = '1';
                $_POST['def_addr'] = $address['def_addr'];
                $_POST['memo'] = $pay_note;
                $_POST['payment']['pay_app_id'] = $payment;
            }
        }

        $obj_mCart = app::get('b2c')->model('cart');
        $member_indent = md5($_POST['member_id'] . kernel::single('base_session')->sess_id());
        $data = $obj_mCart->get_cookie_cart_arr($member_indent,$_POST['member_id']);

        $objCarts = $obj_mCart->get_cart_object($data);
        $is_empty = $obj_mCart->is_empty($objCarts);
        if ($is_empty)
        {
            return $service->send_user_error('购物车为空，操作失败！');
        }

        $order = app::get('b2c')->model('orders');
        $_POST['order_id'] = $order_id = $order->gen_id();
        $order_data = array();

        //加入货币类型。否则会出现前台显示不支持此种支付方式
        $objCurrency = app::get('ectools')->model("currency");
        $aCur = $objCurrency->getDefault();
        $_POST['payment']['currency'] = $aCur['cur_code'];

        $obj_order_create = kernel::single("b2c_order_create");
        $order_data = $obj_order_create->generate($_POST, $member_indent, $msg, $objCarts);

        $result = $obj_order_create->save($order_data, $msg);
        // 与中心交互
        /*$obj_rpc_request_service = kernel::service('b2c.rpc.send.request');

        if ($obj_rpc_request_service && method_exists($obj_rpc_request_service, 'rpc_caller_request'))
        {
            if ($obj_rpc_request_service instanceof b2c_api_rpc_request_interface)
                $obj_rpc_request_service->rpc_caller_request($order_data,'create');
        }
        else
        {
            $obj_order_create->rpc_caller_request($order_data);
            }*/
        //新的版本控制api
        $obj_apiv = kernel::single('b2c_apiv_exchanges_request');
        $obj_apiv->rpc_caller_request($order_data, 'ordercreate');

        // 取到日志模块
        $log_text = "";
        if ($result)
        {
            $log_text = app::get('b2c')->_("订单创建成功！");
        }
        else
        {
            $log_text = app::get('b2c')->_("订单创建失败！");
        }
        $orderLog = app::get('b2c')->model("order_log");
        $sdf_order_log = array(
            'rel_id' => $order_id,
            'op_id' => $this->user->user_id,
            'op_name' => $this->user->user_data['account']['login_name'],
            'alttime' => time(),
            'bill_type' => 'order',
            'behavior' => 'creates',
            'result' => ($result) ? 'SUCCESS' : 'FAILURE',
            'log_text' => $log_text,
        );

        $log_id = $orderLog->save($sdf_order_log);

        if ($result)
        {
            // 订单成功后清除购物车的的信息
            $cart_model = app::get('b2c')->model('cart');
            $cart_model->del_cookie_cart_arr($member_indent);

            $mCartObject = app::get('b2c')->model('cart_objects');
            foreach($cart_objects as $cart_object){
                $mCartObject->remove_object($cart_object['obj_type'], $cart_object['obj_ident'], $msg);
            }

            // 得到物流公司名称
            if ($order_data['order_objects'])
            {
                $itemNum = 0;
                $good_id = "";
                $goods_name = "";
                foreach ($order_data['order_objects'] as $arr_objects)
                {
                    if ($arr_objects['order_items'])
                    {
                        if ($arr_objects['obj_type'] == 'goods')
                        {
                            $obj_goods = app::get('b2c')->model('goods');
                            $good_id = $arr_objects['order_items'][0]['goods_id'];
                            $arr_goods = $obj_goods->dump($good_id);
                        }

                        foreach ($arr_objects['order_items'] as $arr_items)
                        {
                            $itemNum = kernel::single('ectools_math')->number_plus(array($itemNum, $arr_items['quantity']));
                            if ($arr_objects['obj_type'] == 'goods')
                            {
                                if ($arr_items['item_type'] == 'product')
                                    $goods_name .= $arr_items['name'] . ($arr_items['products']['spec_info'] ? '(' . $arr_items['products']['spec_info'] . ')' : '') . '(' . $arr_items['quantity'] . ')';
                            }
                        }
                    }
                }
                $obj_dlytype = app::get('b2c')->model('dlytype');
                $arr_dlytype = $obj_dlytype->dump($order_data['shipping']['shipping_id'], 'dt_name');

                if ($order_data['member_id'])
                {
                    $login_name = kernel::single('b2c_user_object')->get_member_name(null,$order_data['member_id']);
                }
                $arr_updates = array(
                    'order_id' => $order_id,
                    'total_amount' => $order_data['total_amount'],
                    'shipping_id' => $arr_dlytype['dt_name'],
                    'ship_mobile' => $order_data['consignee']['mobile'],
                    'ship_tel' => $order_data['consignee']['telephone'],
                    'ship_addr' => $order_data['consignee']['addr'],
                    'ship_email' => $order_data['consignee']['email'] ? $order_data['consignee']['email'] : '',
                    'ship_zip' => $order_data['consignee']['zip'],
                    'ship_name' => $order_data['consignee']['name'],
                    'member_id' => $order_data['member_id'] ? $order_data['member_id'] : 0,
                    'uname' => (!$order_data['member_id']) ? app::get('b2c')->_('顾客') : $login_name,
                    'itemnum' => count($order_data['order_objects']),
                    'goods_id' => $good_id,
                    'goods_url' => kernel::base_url(1).kernel::url_prefix().app::get('site')->router()->gen_url(array('app'=>'b2c','ctl'=>'site_product','act'=>'index','arg0'=>$good_id)),
                    'thumbnail_pic' => base_storager::image_path($arr_goods['image_default_id']),
                    'goods_name' => $goods_name,
                    'ship_status' => '',
                    'pay_status' => 'Nopay',
                    'is_frontend' => false,
                );
                $order->fireEvent('create', $arr_updates, $order_data['member_id']);
            }
        }

        if ($result)
        {
            $order_num = $order->count(array('member_id' => $order_data['member_id']));
            $obj_mem = app::get('b2c')->model('members');
            $obj_mem->update(array('order_num'=>$order_num), array('member_id'=>$order_data['member_id']));
            return $return = array('order_sn'=>$order_id);
        }
    }

    /**
     * 4.8 查看物流信息
     */
    public function shipping($params,&$service)
    {
        if(!$this->check_sid($params['sid']) ){
            return $service->send_user_error('100001','error sid');
        }
        if(!$params['order_sn'] ){
            return $service->send_user_error('参数错误，order_sn不能为空');
        }else{
            $order_sn = $params['order_sn'];
        }
        $db = kernel::database();
        $logisticstrack = $db->selectrow('select * from sdb_logisticstrack_logistic_log where delivery_id='.$order_sn);
        $return['shipping_sn'] = $logisticstrack['logistic_no'];
        $return['shipping_name'] = $logisticstrack['dly_corp'];
        $return['shipping_data']['timestamp'] = $logisticstrack['dtline'];
        $return['shipping_data']['content'] = $logisticstrack['logistic_log'];

        return $return;
    }
}